import { useEffect, useState } from 'react'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import { FilePreviewState } from '../constants'
import '../text/index.less'
import './index.less'

function MdViewer({ configProps, setLoading, handleError, downloadFile }: FilePreviewState) {
  const [cropped, setCropped] = useState<boolean>(false)
  const [md, setMd] = useState('loading... ...')

  const removeBrokenImage = text => {
    if ((text.startsWith('![image.png]') || text.startsWith('[image.png]')) && !text.endsWith(')')) {
      return ''
    }
    return text
  }

  useEffect(() => {
    fetch(configProps.fileUrl)
      // fetch(`/api/v1/knowledge/download?file_path=${configProps.fileUrl}`)
      .then(response => {
        if (response.ok) {
          return response.text()
        } else {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
      })
      .then(text => {
        const len = text.length
        if (len > 10000) {
          text = text.substring(0, 9700)
          const lines = text.split('\n')
          // 最后一行时图片且不完整时移除最后一行
          lines[lines.length - 1] = removeBrokenImage(lines[lines.length - 1])
          setCropped(true)
          text = lines.join('\n')
        }
        setLoading(false)
        setMd(text)
      })
      .catch(error => {
        console.error('加载md文件出错:', error)
        handleError(`${configProps.title}文件加载失败`)
      })
  }, [md])

  return (
    <div className="markdown-preview-styles min-h-[calc(100vh-200px)]">
      <ReactMarkdown remarkPlugins={[remarkGfm]}>{md}</ReactMarkdown>
      {cropped && (
        <div className="text-preview-cropped">
          <div className="mb-[24px] mt-[8px]">......</div>
          预览时 TXT、LOG、JSON和Markdown文件默认显示前1W个字符，可通过
          <span className="text-download-btn" onClick={() => downloadFile()}>
            下载
          </span>
          查看文件全部内容
        </div>
      )}
    </div>
  )
}
export default MdViewer
